package com.yzy.fly.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.yzy.fly.FlySpringMap;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FlyDynamicRoutingDataSource extends DynamicRoutingDataSource {

    public FlyDynamicRoutingDataSource(List<DynamicDataSourceProvider> providers) {
        super(providers);
    }

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
//        // 检查开启了配置但没有相关依赖
//        checkEnv();
//        // 添加并分组数据源
//        Map<String, DataSource> dataSources = new HashMap<>(16);
//        for (DynamicDataSourceProvider provider : providers) {
//            Map<String, DataSource> dsMap = provider.loadDataSources();
//            if (dsMap != null) {
//                dataSources.putAll(dsMap);
//            }
//        }
//        for (Map.Entry<String, DataSource> dsItem : dataSources.entrySet()) {
//            addDataSource(dsItem.getKey(), dsItem.getValue());
//        }
//        // 检测默认数据源是否设置
//        if (groupDataSources.containsKey(primary)) {
//            log.info("dynamic-datasource initial loaded [{}] datasource,primary group datasource named [{}]", dataSources.size(), primary);
//        } else if (dataSourceMap.containsKey(primary)) {
//            log.info("dynamic-datasource initial loaded [{}] datasource,primary datasource named [{}]", dataSources.size(), primary);
//        } else {
//            log.warn("dynamic-datasource initial loaded [{}] datasource,Please add your primary datasource or check your configuration", dataSources.size());
//        }

        Map<String, DataSource> dataSourceMap = getDataSources();
        String primary = getPrimary();

        FlySpringMap.getInstance().add("DynamicDatasource.Count", dataSourceMap.size());
        FlySpringMap.getInstance().add("DynamicDatasource.Primary", primary);
    }
}
